<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>函数默认值和剩余参数</title>
</head>
<body>
  
</body>

<script type="text/javascript">

  // 1、带参数默认值的函数

  // es5写法
  function add (a, b) {
    a = a || 10
    b = b || 20
    console.log(a + b);
  }
  add(1, 2)
  add(1)
  add()

  // es6写法
  function add1(a = 100, b = 200) {
    console.log(a + b);
  }
  add1(1, 3)
  add1(1)
  add1()

  // 2、默认的表达式也可以是一个函数
  function add2(a, b = getVal(5)) {
    console.log(a + b);
  }
  add2(5)
  add2(5, 5)

  function getVal(val) {
    return val + 5
  }

  // 3、
  let book = {
    title: 'es6进阶',
    author: 'chengjunyu',
    year: 2019
  }
  let bookData_es5 = select_es5(book, 'author', 'year', 'title')
  console.log(bookData_es5);

  // es5写法，arguments，for循环从1开始
  function select_es5(obj) {
    let result = Object.create(null)
    for (let i = 1; i < arguments.length; i++) {
      // console.log(arguments);
      result[arguments[i]] = obj[arguments[i]]
    }
    return result
  }

  // es6写法，剩余参数，由三个点...和一个紧跟着的具名参数指定 ...keys，for循环从0开始
  function select_es6(obj, ...keys) {
    // console.log(keys)
    let result = Object.create(null)
    for (let i = 0; i < keys.length; i++) {
      // console.log(arguments);
      result[keys[i]] = obj[keys[i]]
    }
    return result
  }
  let bookData_es6 = select_es6(book, 'year', 'title', 'author')
  console.log(bookData_es6)

  function checkArgs(...args) {
    console.log('args', args);
    console.log('arguments', arguments);
  }
  checkArgs('a', 'b', 'c')
</script>
</html>